#include "Window.hpp"
#include <SDL2/SDL_image.h>

namespace MA {

SDL_Window* Window::m_window = nullptr;
SDL_Renderer* Window::m_renderer = nullptr;

Window::Window(int width, int height, std::string title)
    : m_width(width), m_height(height)
{
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        SDL_Log("SDL can not initialize! SDL_Error: %s\n", SDL_GetError());
        return;
    }
    if (IMG_Init(IMG_INIT_PNG) < 0) {
        SDL_Log("Image extention can not initialize! IMG_Error: %s\n", IMG_GetError());
        return;
    }

    m_window = SDL_CreateWindow(title.c_str(),
                                SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                m_width, m_height, SDL_WINDOW_SHOWN);
    if (m_window == nullptr) {
        SDL_Log("SDL can not create window! SDL_Error: %s\n", SDL_GetError());
        return;
    }

    m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED);
    if (m_renderer == nullptr) {
        SDL_Log("SDL can not create window! SDL_Error: %s\n", SDL_GetError());
        return;
    }
}

Window::~Window() {
    SDL_DestroyRenderer(m_renderer);
    SDL_DestroyWindow(m_window);
    SDL_Quit();

    m_renderer = nullptr;
    m_window = nullptr;
}

SDL_Window* Window::getWindowPtr() {
    return m_window;
}

SDL_Renderer* Window::getRenderPtr() {
    return  m_renderer;
}

int Window::getWindowWidth() {
    return m_width;
}

int Window::getWindowHeight() {
    return m_height;
}

void Window::setTitle(std::string title) {
    if (m_window == nullptr) return;

    SDL_SetWindowTitle(m_window, title.c_str());
}

void Window::resizeWindow(int width, int height) {
    if (m_window == nullptr) return;

    m_width = width;
    m_height = height;
    SDL_SetWindowSize(m_window, m_width, m_height);
}

void Window::setBGColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
    if (m_renderer == nullptr) return;

    SDL_SetRenderDrawColor(m_renderer, r, g, b, a);
}

void Window::clear() {
    SDL_RenderClear(m_renderer);
}
void Window::flush() {
    SDL_RenderPresent(m_renderer);
}

void Window::close() {
    SDL_DestroyRenderer(m_renderer);
    SDL_DestroyWindow(m_window);

    m_renderer = nullptr;
    m_window = nullptr;
    SDL_Quit();
}

}
